//
//  GameDetailViewController.m
//  NBAPro
//
//  Created by 李广松 on 15/3/2.
//  Copyright © 2015年 WYH. All rights reserved.
//

#import "GameDetailViewController.h"

@implementation GameDetailViewController {
    NSString *gameDate;
    NSString *gameId;
    
    
    UITableView *playerTableView;
    
    NSDictionary *visitorDic;
    NSDictionary *homeDic;
    
    NSArray *playersArr;
    UIScrollView *scrollView;
    SelectView *selectHomeAndVisitorView;
    
    UIView *lineView;
    
}

- (id)initWithGameDate:(NSString *)gamedate AndGameId:(NSString *)gameid {
    self = [super init];
    if (self) {
        gameDate = gamedate;
        gameId = gameid;
    }
    
    return self;
}

- (void)viewDidLoad {
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self getGameDetailInfo];
    
}

#pragma mark - 获取信息


- (void)getGameDetailInfo {
    
    NSString *urlStr = [[NSString alloc] initWithFormat:@"%@game/%@/%@/boxscore.json", API_BASE_URL_NBA_DATA, gameDate, gameId];
    NSURL *url = [[NSURL alloc] initWithString:urlStr];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (!error) {
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            
            [self performSelectorOnMainThread:@selector(getPlayersInfo:) withObject:result waitUntilDone:YES];
        }
    }];
    
    [dataTask resume];
    
}

- (void)getPlayersInfo:(NSDictionary *)result {
    NSDictionary *playersDic = result[@"sports_content"][@"game"];
    
    visitorDic = playersDic[@"visitor"];
    homeDic = playersDic[@"home"];
    
    
    
    if ([homeDic[@"players" ] isKindOfClass:[NSDictionary class]]) {
        playersArr = homeDic[@"players"][@"player"];
    }
    else {
        playersArr = @[@""];
    }
    
    
    [self createAllView];
    
    
    
}


#pragma mark -点击
- (void)touchHomeInfo {
    if ([homeDic[@"players" ] isKindOfClass:[NSDictionary class]]) {
        playersArr = homeDic[@"players"][@"player"];
    }
    else {
        playersArr = @[@""];
    }
    scrollView.contentSize = CGSizeMake(750, (playersArr.count + 1) * 42);
    [playerTableView reloadData];
    [scrollView setContentOffset:CGPointMake(0, 0) animated:NO];
//    selectHomeAndVisitorView = [self createSelectViewWithHomeColor:[UIColor blackColor] AndVisitorColor:[UIColor colorWithRed:88/255.0 green:104/255.0 blue:131/255.0 alpha:1] AndHomeBackgroundColor:[UIColor whiteColor] AndVisitorBackgroundColor:[UIColor clearColor] AndLineFrame:CGRectMake(0, 50 - 3, self.view.frame.size.width / 2, 3)];
    
    [self selectChangeWithHomeTextColor:[UIColor blackColor] AndHomeBackColor:[UIColor whiteColor] AndVisitorTextColor:[UIColor colorWithRed:88/255.0 green:104/255.0 blue:131/255.0 alpha:1] AndVisitorBackColor:[UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1]];
    selectHomeAndVisitorView.cutLine.frame = CGRectMake(0, selectHomeAndVisitorView.cutLine.frame.origin.y, self.view.frame.size.width / 2, 3);
    
    selectHomeAndVisitorView.cutLine.backgroundColor = [GetInfo getTeamColorWithTeamName:homeDic[@"nickname"]];
    
}

- (void)selectChangeWithHomeTextColor:(UIColor *)homeTextColor AndHomeBackColor:(UIColor *)homeBackColor AndVisitorTextColor:(UIColor *)visitorColor AndVisitorBackColor:(UIColor *)visitorBackColor{
    selectHomeAndVisitorView.homeBtn.titleLabel.textColor = homeTextColor;
    selectHomeAndVisitorView.homeBtn.backgroundColor = homeBackColor;
    selectHomeAndVisitorView.visitorBtn.titleLabel.textColor = visitorColor;
    selectHomeAndVisitorView.visitorBtn.backgroundColor = visitorBackColor;
    
}

- (void)touchVisitorInfo {
    if ([visitorDic[@"players" ] isKindOfClass:[NSDictionary class]]) {
        playersArr = visitorDic[@"players"][@"player"];
    }
    else {
        playersArr = @[@""];
    }

    scrollView.contentSize = CGSizeMake(750, (playersArr.count + 1) * 42);
    [scrollView setContentOffset:CGPointMake(0, 0) animated:NO];
    [playerTableView reloadData];
    
//    selectHomeAndVisitorView = [self createSelectViewWithHomeColor:[UIColor colorWithRed:88/255.0 green:104/255.0 blue:131/255.0 alpha:1]  AndVisitorColor:[UIColor blackColor] AndHomeBackgroundColor:[UIColor clearColor] AndVisitorBackgroundColor:[UIColor whiteColor] AndLineFrame:CGRectMake(self.view.frame.size.width / 2, 50 - 3, self.view.frame.size.width / 2, 3)];
    
    [self selectChangeWithHomeTextColor:[UIColor colorWithRed:88/255.0 green:104/255.0 blue:131/255.0 alpha:1] AndHomeBackColor:[UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1] AndVisitorTextColor:[UIColor blackColor] AndVisitorBackColor:[UIColor whiteColor]];
    selectHomeAndVisitorView.cutLine.frame = CGRectMake(self.view.frame.size.width / 2, selectHomeAndVisitorView.cutLine.frame.origin.y, self.view.frame.size.width / 2, 3);
    selectHomeAndVisitorView.cutLine.backgroundColor = [GetInfo getTeamColorWithTeamName:visitorDic[@"nickname"]];

}


- (void)touchReturn {
    //    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}



#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return playersArr.count + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *identifier = @"cell";
    GameInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (indexPath.row == 0) {
        if (!cell) {
            cell = [self returnFirstCellInfo];
        }
    }
    else {
        if (!cell) {
            cell = [[GameInfoTableViewCell alloc] initWithFont:12];
        }

        if (indexPath.row == 1) {
            cell.topLine.frame = CGRectMake(0, 0, 750, 1);
            cell.topLine.backgroundColor = [UIColor colorWithRed:132/255.0 green:132/255.0 blue:132/255.0 alpha:1];
        }
        if (indexPath.row == playersArr.count) {
            cell.downLine.hidden = YES;
        }
        
        if ([playersArr[indexPath.row - 1] isKindOfClass:[NSDictionary class]]) {
            cell = [self returnOtherCellInfoWithCell:cell AndIndex:(int)indexPath.row];
        }
    }

    
    return cell;
}




#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 42;
}


#pragma mark - 界面

- (void)createAllView {
    UIView *titleView = [self createTopViewWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
    [self.view addSubview:titleView];
    
    [self createReturnIcon];
    
    [self createSelectView];
    
    scrollView = [self createScrollViewWithFrame:CGRectMake(0, selectHomeAndVisitorView.frame.origin.y + selectHomeAndVisitorView.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - titleView.frame.size.height - selectHomeAndVisitorView.frame.size.height - 80) AndContentSize:CGSizeMake(750, (playersArr.count + 1) * 42)];
    [self.view addSubview:scrollView];
    
    playerTableView = [self createTableViewWithFrame:CGRectMake(0, 0, 750, (playersArr.count + 1) * 42)];
    [scrollView addSubview:playerTableView];
    
}

- (void)createSelectView {
    selectHomeAndVisitorView = [[SelectView alloc] initWithFrame:CGRectMake(0, 200, self.view.frame.size.width, 50)];
    [self.view addSubview:selectHomeAndVisitorView];
    selectHomeAndVisitorView.cutLine.backgroundColor = [GetInfo getTeamColorWithTeamName:homeDic[@"nickname"]];

    [selectHomeAndVisitorView.homeBtn setTitle:[[NSString alloc] initWithFormat:@"%@ %@", homeDic[@"city"], homeDic[@"nickname"]] forState:UIControlStateNormal];
    [selectHomeAndVisitorView.visitorBtn setTitle:[[NSString alloc] initWithFormat:@"%@ %@", visitorDic[@"city" ], visitorDic[@"nickname"]] forState:UIControlStateNormal];
    
    [selectHomeAndVisitorView.homeBtn addTarget:self action:@selector(touchHomeInfo) forControlEvents:UIControlEventTouchUpInside];
    [selectHomeAndVisitorView.visitorBtn addTarget:self action:@selector(touchVisitorInfo) forControlEvents:UIControlEventTouchUpInside];
}



- (UITableView *)createTableViewWithFrame:(CGRect)frame {
    UITableView *tableView = [[UITableView alloc] initWithFrame:frame];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.userInteractionEnabled = NO;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    return tableView;
}

- (UIScrollView *)createScrollViewWithFrame:(CGRect)frame AndContentSize:(CGSize)size {
    UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:frame];
    scroll.contentSize = size;
    scroll.backgroundColor = [UIColor whiteColor];
    scroll.bounces = NO;
    scroll.showsVerticalScrollIndicator = FALSE;
    scroll.showsHorizontalScrollIndicator = FALSE;
    
    
    return scroll;
    
}

- (void)createReturnIcon {
    
    UIImage *returnImg = [UIImage imageNamed:@"return"];
    UIImageView *returnImgView = [[UIImageView alloc] initWithFrame:CGRectMake(25, 20, returnImg.size.width, returnImg.size.height)];
    returnImgView.image = returnImg;
    [self.view addSubview:returnImgView];
    
    UIButton *returnBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, returnImgView.frame.origin.y, returnImg.size.width + 25, returnImg.size.height)];
    [returnBtn addTarget:self action:@selector(touchReturn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:returnBtn];
    
}
- (UIView *)createTopViewWithFrame:(CGRect)frame {
    UIView *view = [[UIView alloc] initWithFrame:frame];
    view.backgroundColor = [GetInfo getTeamColorWithTeamName:homeDic[@"nickname"]];
    
    UIView *homeTeamView = [self createLeftTeamViewWithFrame:CGRectMake(0, 0, self.view.frame.size.width / 2, frame.size.height) AndHomeOrVisitor:@"home" AndScore:homeDic[@"score"] AndTeam:homeDic[@"nickname"] AndCity:homeDic[@"city"] AndImageName:[homeDic[@"team_key"] lowercaseString]];
    [view addSubview:homeTeamView];
    
    UIView *visitorTeamView = [self createRightTeamViewWithFrame:CGRectMake(self.view.frame.size.width / 2, 0, self.view.frame.size.width / 2, frame.size.height) AndHomeOrVisitor:@"visitor" AndScore:visitorDic[@"score"] AndTeam:visitorDic[@"nickname"] AndCity:visitorDic[@"city"] AndImageName:[visitorDic[@"team_key"] lowercaseString]];
    [view addSubview:visitorTeamView];
    
    
    UILabel *cutLineLab = [CreateControl createLabelWithFrame:CGRectMake(self.view.frame.size.width / 2 , view.frame.size.height / 2 - 20, 0.5, 70) AndText:nil AndTextColor:[UIColor clearColor] AndBackgroundColor:[UIColor whiteColor] AndTextFont:0];
    [view addSubview:cutLineLab];
    
    
    UILabel *qrtLab = [CreateControl createLabelWithFrame:CGRectMake(0, cutLineLab.frame.origin.y - 30, self.view.frame.size.width, 15) AndText:@"Q4 0:00" AndTextColor:[UIColor whiteColor] AndBackgroundColor:[UIColor clearColor] AndTextFont:15];
    [view addSubview:qrtLab];
    
    
    return view;
}

//
//- (UIView *)createSelectViewWithHomeColor:(UIColor *)homeColor AndVisitorColor:(UIColor *)visitorColor AndHomeBackgroundColor:(UIColor *)homeBackColor AndVisitorBackgroundColor:(UIColor *)visitorBackColor AndLineFrame:(CGRect)lineFrame{
//    
//    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 200, self.view.frame.size.width, 50)];
//    view.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1];
//    
//    NSString *homeNameStr = [[NSString alloc] initWithFormat:@"%@ %@", homeDic[@"city"], homeDic[@"nickname"]];
//    UIButton *homeBtn = [CreateControl createButtonWithFrame:CGRectMake(0, 0, self.view.frame.size.width / 2, view.frame.size.height - 3) AndText:[homeNameStr uppercaseString] AndTextColor:homeColor AndBackgroundColor:homeBackColor AndTextFont:14];
//    [homeBtn addTarget:self action:@selector(touchHomeInfo) forControlEvents:UIControlEventTouchUpInside];
//    [view addSubview:homeBtn];
//    
//    NSString *visitorStr = [[NSString alloc] initWithFormat:@"%@ %@", visitorDic[@"city" ], visitorDic[@"nickname"]];
//    UIButton *visitorBtn = [CreateControl createButtonWithFrame:CGRectMake(self.view.frame.size.width / 2, 0, self.view.frame.size.width / 2, homeBtn.frame.size.height) AndText:[visitorStr uppercaseString] AndTextColor:visitorColor AndBackgroundColor:visitorBackColor AndTextFont:14];
//    [visitorBtn addTarget:self action:@selector(touchVisitorInfo) forControlEvents:UIControlEventTouchUpInside];
//    [view addSubview:visitorBtn];
//    
//    //下 线
//    lineView = [[UIView alloc] initWithFrame:lineFrame];
//    lineView.backgroundColor = [GetInfo getTeamColorWithTeamName:homeDic[@"nickname"]];
//    [view addSubview:lineView];
//    
//    return view;
//}
//
- (UIView *)createLineWithFrame:(CGRect)frame {
   
    UIView *view = [[UIView alloc] initWithFrame:frame];
    view.backgroundColor = [UIColor colorWithRed:133/255.0 green:133/255.0 blue:133/255.0 alpha:1];
    
    return view;
}


- (UIView *)createLeftTeamViewWithFrame:(CGRect)frame AndHomeOrVisitor:(NSString *)text AndScore:(NSString *)score AndTeam:(NSString *)teamStr AndCity:(NSString *)city AndImageName:(NSString *)imageStr {
    
    UIView *view = [[UIView alloc] initWithFrame:frame];
    
    UILabel *homeLabel = [CreateControl createLabelWithFrame:CGRectMake(frame.size.width - 30 - 31 - 2, frame.size.height / 2 - 15, 31, 20) AndText:text AndTextColor:[UIColor whiteColor] AndBackgroundColor:[UIColor clearColor] AndTextFont:11];
    [view addSubview:homeLabel];

    UILabel *teamPotLab = [self createSizeLabelWithPoint:CGPointMake(homeLabel.frame.origin.x + homeLabel.frame.size.width / 2, homeLabel.frame.origin.y + 20) AndPointStr:score AndFont:30];
    [view addSubview:teamPotLab];
    
    UIImageView *teamImgView = [[UIImageView alloc] initWithFrame:CGRectMake(25, 50, 85, 85)];
    teamImgView.image = [UIImage imageNamed:imageStr];
    [view addSubview:teamImgView];
    
    UILabel *teamCityLab = [self createSizeLabelWithPoint:CGPointMake(teamImgView.frame.origin.x + teamImgView.frame.size.width / 2, teamImgView.frame.origin.y + teamImgView.frame.size.height) AndPointStr:city AndFont:11];
    UILabel *teamNameLab = [self createSizeLabelWithPoint:CGPointMake(teamImgView.frame.origin.x + teamImgView.frame.size.width / 2, teamCityLab.frame.origin.y + teamCityLab.frame.size.height) AndPointStr:teamStr AndFont:11];
    [teamNameLab setFont:[UIFont fontWithName:FONT_Hel size:11]];

    
    [view addSubview:teamCityLab];
    [view addSubview:teamNameLab];
    
    
    return view;
}

- (UILabel *)createSizeLabelWithPoint:(CGPoint)point AndPointStr:(NSString *)string AndFont:(float)font {
    CGSize pointsSize = [string sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]}];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(point.x - pointsSize.width / 2 + 1, point.y , pointsSize.width + 2, font + 3)];
    label.text = string;
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:font];
    label.textAlignment = NSTextAlignmentCenter;
    return label;
}


- (UIView *)createRightTeamViewWithFrame:(CGRect)frame AndHomeOrVisitor:(NSString *)text AndScore:(NSString *)score AndTeam:(NSString *)teamStr AndCity:(NSString *)city AndImageName:(NSString *)imageStr {
    
    UIView *view = [[UIView alloc] initWithFrame:frame];
    UILabel *visitorLabel = [CreateControl createLabelWithFrame:CGRectMake(30, frame.size.height / 2 - 15, 40, 20) AndText:text AndTextColor:[UIColor whiteColor] AndBackgroundColor:[UIColor clearColor] AndTextFont:11];
    [view addSubview:visitorLabel];
    
    
    UILabel *teamPotLab = [self createSizeLabelWithPoint:CGPointMake(visitorLabel.frame.origin.x + visitorLabel.frame.size.width / 2, visitorLabel.frame.origin.y + 20) AndPointStr:score AndFont:30];
    [view addSubview:teamPotLab];
    
    UIImageView *teamImgView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 25 - 85, 50, 85, 85)];
    teamImgView.image = [UIImage imageNamed:imageStr];
    [view addSubview:teamImgView];
    
    
    UILabel *teamCityLab = [self createSizeLabelWithPoint:CGPointMake(teamImgView.frame.origin.x + teamImgView.frame.size.width / 2, teamImgView.frame.origin.y + teamImgView.frame.size.height) AndPointStr:city AndFont:11];
    UILabel *teamNameLab = [self createSizeLabelWithPoint:CGPointMake(teamImgView.frame.origin.x + teamImgView.frame.size.width / 2, teamCityLab.frame.origin.y + teamCityLab.frame.size.height) AndPointStr:teamStr AndFont:11];
    [teamNameLab setFont:[UIFont fontWithName:FONT_Hel size:11]];

    [view addSubview:teamCityLab];
    [view addSubview:teamNameLab];
    
    
    return view;
}


#pragma mark - other

- (GameInfoTableViewCell *)returnFirstCellInfo {
    GameInfoTableViewCell *cell = [[GameInfoTableViewCell alloc] initWithFont:16];
    cell.positionLabel.text = @"P";
    cell.ptsLabel.text = @"PTS";
    cell.astLabel.text = @"AST";
    cell.rebLabel.text = @"REB";
    cell.fgLabel.text = @"FG";
    cell.blkLabel.text = @"BLK";
    cell.stlLabel.text = @"STL";
    cell.threePtLabel.text = @"3PT";
    cell.ptLabel.text = @"PT";
    cell.toLabel.text = @"TO";
    cell.topLine.hidden = YES;
    cell.downLine.frame = CGRectMake(0, 42 - 1, 750, 1);
    cell.downLine.backgroundColor = [UIColor colorWithRed:132/255.0 green:132/255.0 blue:132/255.0 alpha:1];
    
    
    return cell;
}

- (GameInfoTableViewCell *)returnOtherCellInfoWithCell:(GameInfoTableViewCell *)cell AndIndex:(int)indexInt{
    NSDictionary *playerInfo = playersArr[indexInt - 1];
    
    
    NSString *positionStr = playerInfo[@"starting_position"];
    if ([positionStr isEqualToString:@""]) {
        positionStr = @"-";
    }
    
    NSString *nameStr = [[NSString alloc] initWithFormat:@"%@ %@.%@", playersArr[indexInt - 1][@"jersey_number"], [playersArr[indexInt - 1][@"first_name"] substringToIndex:1], playersArr[indexInt - 1][@"last_name"]];
    
    NSString *reboundStr = [[NSString alloc] initWithFormat:@"%i", [playerInfo[@"rebounds_offensive"] intValue] + [playerInfo[@"rebounds_defensive"] intValue]];
    NSString *fieldGoalStr = [[NSString alloc] initWithFormat:@"%@-%@", playerInfo[@"field_goals_made"], playerInfo[@"field_goals_attempted"]];
    NSString *threePointerStr = [[NSString alloc] initWithFormat:@"%@-%@", playerInfo[@"three_pointers_made"], playerInfo[@"three_pointers_attempted"]];
    NSString *freeThrowStr = [[NSString alloc] initWithFormat:@"%@-%@",playerInfo[@"free_throws_made"], playerInfo[@"free_throws_attempted"]];
    
    cell.nameLabel.text = nameStr;
    cell.positionLabel.text = positionStr;
    cell.ptsLabel.text = playerInfo[@"points"];
    cell.astLabel.text = playerInfo[@"assists"];
    cell.rebLabel.text = reboundStr;
    cell.fgLabel.text = fieldGoalStr;
    cell.blkLabel.text = playerInfo[@"blocks"];
    cell.stlLabel.text = playerInfo[@"steals"];
    cell.threePtLabel.text = threePointerStr;
    cell.ptLabel.text = freeThrowStr;
    cell.toLabel.text = playerInfo[@"fouls"];
    
    return cell;
}


- (BOOL)prefersStatusBarHidden {
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end
